<%@ page contentType = "text/html;charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="/resources/knit/css/knit.css">
  <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!--[if lt IE 9]>
    <script src="/resources/knit/js/html5shiv.js"></script>
    <script src="/resources/knit/js/respond.min.js"></script>
  <![endif]-->
  
  <style type="text/css" media="screen">
    .editor { 
        position: absolute !important;
        font: 'consolas' !important;
        top: 40px;
        right: 0;
        bottom: 0;
        left: 0;
    }
	</style>
</head>
<body>
<ul class="nav nav-tabs">
   <li class="menu">
    <a class="dropdown-toggle" data-toggle="dropdown" href="#">
      menu <span class="caret"></span>
    </a>
    <ul class="dropdown-menu" role="menu">
      <li><a href="javascript:addEditor();">탭 추가</a></li>
      <li class="divider"></li>
      <li><a href="javascript:changeTheme('chrome');">테마:chrome</a></li>
      <li><a href="javascript:changeTheme('eclipse');">테마:eclipse</a></li>
      <li><a href="javascript:changeTheme('xcode');">테마:XCode</a></li>
      <li><a href="javascript:changeTheme('terminal');">테마:terminal</a></li>
      <li><a href="javascript:changeTheme('cobalt');">테마:cobalt</a></li>
    </ul>
  </li>

</ul>
<div id="editor0" class="editor"></div>

<form name="exec" action="/execute" method="post" target="result">
	<input type="hidden" name="dbid" value="">
	<input type="hidden" name="query" value="">
</form>
<script src="/resources/knit/js/jquery.js"></script>
<script src="/resources/knit/js/knit.min.js"></script>
<script src="/resources/ace/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
    var editor = {};
    
    var Range = ace.require('ace/range').Range;
    var Selection = ace.require('ace/selection').Selection;
	var Search = ace.require('ace/search').Search;
    var defaultTheme = getCookie('wdbc_theme');
    var editorNo = 0;
    var size = 0;

    function createEditor(no){
    	var e = ace.edit("editor"+no);
        var size = 1;
        e.setTheme('ace/theme/' + defaultTheme);
        e.getSession().setMode("ace/mode/sql");
        e.commands.addCommand({
            name: 'run',
            bindKey: {win: 'Ctrl-Enter',  mac: 'Command-Enter'},
            exec: function(editor) {
				run();
            },
            readOnly: true // false if this command should not apply in readOnly mode
        });
        e.commands.addCommand({
            name: 'plan',
            bindKey: {win: 'Ctrl-p',  mac: 'Command-Shift-p'},
            exec: function(editor) {
				plan();
            },
            readOnly: true // false if this command should not apply in readOnly mode
        });

    	return e;    
    }
    
    function addEditor(){
    	var newEditor = $('<div id="editor' + size + '" class="editor" style="display:none"></div>');
    	var oldEditor = $('div.editor');
    	$('ul.nav').after(newEditor);
    	editor[size] = createEditor(size);
        oldEditor.hide();
        newEditor.show();
        
        var newTab = $('<li class="active" id="tab'+size+'"><a href="javascript:selectTab('+size+');">editor'+size+'</a></li>');
        
        $('li.active').removeClass('active');
        
        $('li.menu').before(newTab);
        editorNo = size;
        editor[size].focus();
        size++;
    	
    }
    
    function selectTab(no){
    	$('li.active').removeClass('active');
    	$('#tab'+no).addClass('active');
    	$('#editor' + editorNo).hide();
    	$('#editor' + no).show();
    	editorNo = no;
    	editor[no].focus();
    }
    
    function changeTheme(theme){
    	for(i=0;i<size;i++){
    		editor[i].setTheme('ace/theme/' + theme);
    	}
    	defaultTheme = theme;
    	document.cookie = 'wdbc_theme='+theme+';';
    }
    
    function getQuery(){
    	var _editor = editor[editorNo];
    	var _session = _editor.getSession();
    	var query =  _editor.getSelectedText();
    	if(query != ''){
    		return query;
    	}
    	var start = _editor.find(';', {backwards:true, wrap:false}, false);
    	var end = _editor.find(';', {backwards:false, wrap:false}, false);
    	if(start == undefined){
    		start = {end:{row:0,column:0}};
    	}
    	if(end == undefined){
    		var lastRow = _session.getLength()-1;
    		var lastText = _session.getLine(lastRow);
    		end = {start:{row:lastRow, column:lastText.length}};
    	}
    	var r = new Range(start.end.row, start.end.column, end.start.row, end.start.column);
    	query = _session.getTextRange(r);
    	_editor.find(query, {backwards:true, wrap:true}, false);
		return query;
    }
    
    function getQueryRange(start, end){
    	
    }
    function run(){
    	var query = getQuery();
    	execute(query);
    }
    function plan(){
    	var query = getQuery();
    	executeplan(query);
    }
    
    function execute(query){
    	if(query.trim() ==''){
    		return;
    	}
    	var form = document.exec;
    	if(exec.dbid.value == ''){
    		alert('db연결 필요');
    		return;
    	}
    	form.action='/execute';
    	form.query.value =query;
    	
    	form.submit();
    }
	
    function executeplan(query){
    	if(query.trim() ==''){
    		return;
    	}
    	var form = document.exec;
    	if(exec.dbid.value == ''){
    		alert('db연결 필요');
    		return;
    	}
    	form.action='/plan';
    	form.query.value =query;
    	
    	form.submit();

    }
	function getCookie(cookieName) {
		var search = cookieName + "=";
		var cookie = document.cookie;
		if (cookie.length > 0) {
			var startIndex = cookie.indexOf(cookieName);
			if (startIndex != -1) {
				startIndex += cookieName.length;
				var endIndex = cookie.indexOf(";", startIndex);
				if (endIndex == -1)
					endIndex = cookie.length;
				return cookie.substring(startIndex + 1, endIndex);
			} else {
				return "chrome";
			}
		} else {
			return "chrome";
		}
	}
	function getEditorCount(){
		return size;
	}
	
	function getEditorText(idx){
		var _session = editor[idx].getSession();
		return _session.getValue();
	}
	
	function setEditorStatus(value){
		addEditor();
		var _session = editor[editorNo].getSession();
		_session.setValue(value);
		selectTab(0);
	}
	
	function getTheme(){
		return defaultTheme;	
	}
	parent.sendAlert('loaded');
</script>

</body>
</html>
